import React, { useState, useEffect } from "react";
import axios from "axios";

// 2. async
const request = async (url) => {
    const res = await axios.get(url);
    const data = res.data;
    if (data.code !== 200) {
        alert("服务器开小差了");
        return {};
    }
    return data.data;
};

//Hook封装
const useUser = id => {
    const [user, setUser] = useState({});
    // 加载
    const [loading, setLoading] = useState(true);
    const url = `https://xiaozhu.run/api/user/${id}`;

    const getUser = async () => {
        const user = await request(url);
        setLoading(false);
        setUser(user);
    };
    useEffect(() => getUser(), [id]);
    return [user, loading];
}
const GetUser = () => {
    const [id, setId] = useState(9527)
    const [user, loading] = useUser(id);
    const [user2, loading2] = useUser(id + 1);
    return (
        <div>
            <button onClick={() => { setId(id + 1); }}>Get User {id}</button>
            {loading && <span>Loading...</span>}
            <div>Email: {user.email}</div>
            <div>Name: {user.username}</div>

            <div>Email2: {user2.email}</div>
            <div>Name2: {user2.username}</div>
        </div>
    );
};
/*
//1.header=函数
// <Parent header={()=>{console.log('dq');}} >
const Parent = props => {
    return (
        <div>
            {props.header} Parent{props.children}
        </div>);
}
export default () => (
    <Parent header={() => { console.log('dq'); }} >
        <GetUser />
        <GetUser />
    </Parent>
);

//2.header=标签
//<Parent header={<h3>头部</h3>} >
const Parent = props => {
    return (
        <div>
            {props.header} Parent{props.children}
        </div>);
}
export default () => (
    <Parent header={<h3>头部</h3>} >
        <GetUser />
        <GetUser />
    </Parent>
);
// 3.header=类组件
//   return <Parent header={<Header/>} > 
const Parent = props => {
    return (
        <div>
            {props.header} Parent{props.children}
        </div>);
}
export default () => {
    class Header extends React.PureComponent {
        render() {
            return (<h1>头部2</h1>);
        }
    };

    return <Parent header={<Header />} >
        <GetUser />
        <GetUser />
    </Parent>
};
*/